<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Jialeo\LaravelSchemaExtend\Schema;
use App\Models\OpenShop\InvestmentPromotion\OpenShopMainProcessModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderModel;

class AddChildOrderToMainProcess extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('open_shop_main_process', function (Blueprint $table) {
            $table->string('orderNo')->default('')->comment('流程订单号')->after('step');
            $table->unsignedBigInteger('pid')->default(0)->comment('主订单main表id')->after('orderNo');
            $table->unsignedTinyInteger('childOrder')->default(0)->comment('0主订单 1订单')->after('pid');
        });

        try {

            // 填充pid，生产都是主订单，无脑同步
            OpenShopMainProcessModel::query()->update(['pid' => \Illuminate\Support\Facades\DB::raw('id')]);

            // 填充历史orderNo
            OpenShopMainProcessModel::query()->where('orderNo', '')->get()->each(function ($item) {
                $item->orderNo = (string)OpenShopSignOrderModel::query()
                                                               ->where('mainProcessId', $item->id)
                                                               ->value('orderNo');
                $item->save();
            });
        } catch (\Exception $e) {
            dump($e);
        }
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('open_shop_main_process', function (Blueprint $table) {
            $table->dropColumn('orderNo');
            $table->dropColumn('pid');
            $table->dropColumn('childOrder');
        });
    }
}
